package com.yili.oa.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yili.oa.entity.SearchBase;
import com.yili.oa.entity.TableBase;
import com.yili.oa.models.Admin;
import com.yili.oa.service.AdminService;
import com.yili.oa.utils.Exception.AjaxException;
import com.yili.oa.utils.ListUtils;
import com.yili.oa.vo.request.AdminReq;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lxr
 * @version v0.01
 * @date 2019/7/25 0025
 * @email 200890949@qq.com
 * @remark 代理列表
 */
@Controller
@RequestMapping("admin")
public class AdminApi {

    @Autowired
    private AdminService adminService;

    @PostMapping("/changeStatus")
    @ResponseBody
    public String add(@RequestBody AdminReq adminReq){
        Integer id = Integer.valueOf(adminReq.getId());
        adminService.update(id,adminReq.getState());
        return "success";
    }

    @GetMapping("/getList")
    @ResponseBody
    public TableBase getList(SearchBase search){
        Admin user = (Admin) SecurityUtils.getSubject().getSession().getAttribute("admin");
        PageHelper.startPage(search.getPage(),search.getLimit());
        List<Admin> list = new ArrayList<>();
        if (user.getIsAdmin().equals(1)){
            list = adminService.getList(search,null);
        }else {
            list = adminService.getList(search, user.getUsername());
        }
        PageInfo pageInfo = new PageInfo<>(list,search.getLimit());
        TableBase tableBase = new TableBase();
        tableBase.setData(list);
        tableBase.setCode(0);
        tableBase.setMsg("");
        tableBase.setCount(pageInfo.getTotal());
        return tableBase;
    }

    /**
     * 重置用户密码
     * @return
     */
    @PostMapping("/reset")
    @ResponseBody
    public String userEditButton(@RequestBody Integer dealerId){
        Admin user = (Admin) SecurityUtils.getSubject().getSession().getAttribute("admin");
        if (user==null){
            return "error";
        }
        adminService.reset(dealerId);
        return "success";
    }

    @GetMapping
    @ResponseBody
    public Admin getById(){
        Admin user = (Admin) SecurityUtils.getSubject().getSession().getAttribute("admin");
        SearchBase search = new SearchBase();
        search.setId(user.getUsername());
        List<Admin> list = adminService.getList(search,null);
        if(ListUtils.isNullOrEmpty(list)){
            return new Admin();
        }else {
            return list.get(0);
        }
    }
}
